import FingerprintJS from '@fingerprintjs/fingerprintjs'
import http from './http'

const DEFAULTSHARE_INFO = {
  title: '新康泰克变天守护计划',
  desc: '天气突变易感冒 新康泰克守护到',
  thumb: 'https://contac-moji.hawnlink.cn/share.png?v=1.0.0',
}

const requireContext = require.context(
  '../assets',
  true,
  /\.(png|jpg|svg|webp)$/,
)

const requireAll = (context: any) => context.keys().map(context)
const images = requireAll(requireContext)

export async function wxAuth() {
  const { data } = await http.get(
    `/api/contac/moji/wxAuth?url=${window.location.href}`,
  )
  window.location.href = data
}

export function isMojiApp() {
  const ua: string = window.navigator.userAgent.toLowerCase()
  if (window?.JsSdk && ua.includes('moji'))
    return true
  return false
}

export function isWeixin(): boolean {
  const ua = window.navigator.userAgent.toLowerCase()
  return !!ua.match(/micromessenger/i)
}

export function UpdateWxShare(options?: {
  title?: string
  desc?: string
  link?: string
  imgUrl?: string
}) {
  const shareData = {
    title: DEFAULTSHARE_INFO.title,
    desc: DEFAULTSHARE_INFO.desc,
    link: `${window.location.origin}`,
    imgUrl: DEFAULTSHARE_INFO.thumb,
    ...options,
  }

  try {
    const { wx } = window
    wx.onMenuShareAppMessage(shareData)
    wx.onMenuShareTimeline(shareData)
    wx.updateAppMessageShareData(shareData)
    wx.updateTimelineShareData(shareData)

    window.WeixinJSBridge.call('showOptionMenu')
  }
  catch {}
}
export async function initWXConfig() {
  if (!isWeixin())
    return

  const { data } = await http.get(
    `/api/contac/moji/jssdk?url=${encodeURIComponent(window.location.href)}`,
  )
  const { wx } = window

  if (!data)
    return

  wx?.config({
    debug: false,
    appId: data.appId,
    timestamp: data._wxTimestamp,
    nonceStr: data._wxNoncestr,
    signature: data._wxSignature,
    jsApiList: [
      'onMenuShareAppMessage',
      'onMenuShareTimeline',
      'updateAppMessageShareData',
      'updateTimelineShareData',
    ],
  })

  wx?.ready(() => {
    UpdateWxShare()
  })
  wx?.error((error: any) => {
    console.warn('wx.error is', error)
  })
}

// 预加载图片
export async function PreLoadImages() {
  let imageFetchCount: number = 0

  return new Promise((reoslve, reject) => {
    images.forEach((path: string) => {
      const i = new Image()
      i.src = path
      i.onload = function () {
        imageFetchCount++
        if (imageFetchCount >= images.length) {
          reoslve(true)
        }
      }

      i.onerror = function (e) {
        reject(e)
      }
    })
  })
}

// 获取设备指纹（code）
export function getDeviveCode(): Promise<string> {
  return new Promise((resolve) => {
    const fpPromise = FingerprintJS.load()
    fpPromise
      .then(fp => fp.get())
      .then((result) => {
        resolve(result.visitorId)
      })
  })
}
